package br.com.quiz.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.HashMap;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import br.com.quiz.factory.ConexaoFactory;


public class ReportUtil {

	public static final String CAMINHO_RELATORIO_ALUNO_PARAMETRO_AMBIGUO = "/relatorios/relatorio_aluno_zebrado_username_ambos.jasper";
	public static final String NOME_RELATORIO_ALUNO_PARAMETRO_AMBIGUO="RelatorioAluno.pdf";
	
	
	public static void gerarRelatorio(String pertencente) throws JRException, SQLException, IOException {
		String caminho = null, nome = null;
		if(pertencente.equals("aluno")){
			caminho=CAMINHO_RELATORIO_ALUNO_PARAMETRO_AMBIGUO;
			nome=NOME_RELATORIO_ALUNO_PARAMETRO_AMBIGUO;
		}

			InputStream report = FacesContext.getCurrentInstance()
					.getExternalContext()
					.getResourceAsStream(caminho);

			JasperPrint print = JasperFillManager.fillReport(caminho, null,
					ConexaoFactory.conectar());
			byte[] bytes = JasperExportManager.exportReportToPdf(print);
			if (bytes != null) {				
				HttpServletResponse response = JSFUtil.getResponse();
				response.setContentType("application/pdf");
				response.setHeader("Content-disposition",
						"attachment;filename="+nome);
				response.setContentLength(bytes.length);
				response.getOutputStream().write(bytes, 0, bytes.length);
				response.getOutputStream().flush();
				response.flushBuffer();
				JSFUtil.responseComplete();
			}

	}
	
	public static void gerarRelatorio(String pertencente, HashMap<String, Object> parametros) throws JRException, SQLException, IOException {
		String caminho = null, nome = null;
		if(pertencente.equals("aluno")){
			caminho=CAMINHO_RELATORIO_ALUNO_PARAMETRO_AMBIGUO;
			nome=NOME_RELATORIO_ALUNO_PARAMETRO_AMBIGUO;
		}
		

			InputStream report = FacesContext.getCurrentInstance()
					.getExternalContext()
					.getResourceAsStream(caminho);

			JasperPrint print = JasperFillManager.fillReport(caminho, parametros,
					ConexaoFactory.conectar());
			byte[] bytes = JasperExportManager.exportReportToPdf(print);
			if (bytes != null) {				
				HttpServletResponse response = JSFUtil.getResponse();
				response.setContentType("application/pdf");
				response.setHeader("Content-disposition",
						"attachment;filename="+nome);
				response.setContentLength(bytes.length);
				response.getOutputStream().write(bytes, 0, bytes.length);
				response.getOutputStream().flush();
				response.flushBuffer();
				JSFUtil.responseComplete();
			}

	}
	

}